#include "ThreadPool.hpp"
#include "Thread.hpp"
#include <unistd.h>

namespace ln{

ThreadPool::ThreadPool(size_t threadNum,size_t queSize)
    :_threads()
     ,_threadNum(threadNum)
     ,_taskque(queSize)
     ,_queSize(queSize)
     ,_isExit(false)
{

}

ThreadPool::~ThreadPool(){
    if(!_isExit){
        stop();
    }
}

void ThreadPool::start(){
    for(size_t i = 0; i < _threadNum; ++i){
        unique_ptr<Thread> thread(new Thread(
                    std::bind(&ThreadPool::doTask,this)
                                            ));
        _threads.push_back(std::move(thread));
    }

    for(auto & thread : _threads){
        thread->start();
    }
}

void ThreadPool::stop(){
    while(!_taskque.empty()){
        sleep(1);
    }

    _isExit = true;
    _taskque.wakeup();

    for(auto & thread : _threads){
        thread->join();
    }
}

void ThreadPool::addTask(Task && task){
    if(task){
        _taskque.push(std::move(task));
    }
}

void ThreadPool::doTask(){
    while(!_isExit){
        Task task = _taskque.pop();
        if(task){
            task();
        }
    }
}

}//end of namespace ln
